'use strict';
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
    TextInput,
    TouchableWithoutFeedback,
    Platform,
    ActivityIndicator,
    ScrollView
} from 'react-native';
import Global from '../Commom/GlobalConst';
import ForgotPasswordContainer from '../Containers/ForgotPasswordContainer';
import Main from '../Containers/Main';
import Toast from '../Utils/toast';
import {ThirdLoginAction, userInfo, thirdLogin} from '../Action/UserAction';
import PerfectInformationContainer from '../Containers/PerfectInformationContainer';
import UserAPIService from '../Commom/UserAPIService';
import * as types from '../Commom/ActionConst';

var {NativeModules} = require('react-native');
export default class LoginPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputUserName: '',
            inputPassword: '',
            submitting: false,
        }
        this.closeKeybord = this.closeKeybord.bind(this);
    }

     closeKeybord() {
        TextInput.State.blurTextInput(TextInput.State.currentlyFocusedField());
    }

    componentDidMount() {
        storage.remove({
            key: Global.Const.storagekeyLogin
        });
    }

    ClickAction(number) {
        switch (number) {
            case 0:
                if (this.state.inputUserName.length == 0) {
                    Toast.show('请输入您的账号');
                    return;
                }
                if (this.state.inputUserName.length != 11) {
                    Toast.show('请输入正确的账号');
                    return;
                }
                if (this.state.inputPassword.length == 0) {
                    Toast.show('请输入您的密码');
                    return;
                }
                if (this.state.inputPassword.length < 6 || this.state.inputPassword.length > 20) {
                    Toast.show('您的密码格式不正确');
                    return;
                }
                this.setState({
                    submitting: true,
                });
                const {dispatch} = this.props;
                UserAPIService.login(this.state.inputUserName, this.state.inputPassword, Global.Const.registeredId).then((ret)=> {
                    if (ret.info_completed == true) {
                        Global.Const.token = ret.token;
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        dispatch(userInfo(ret.token, Global.Const.registeredId));
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.popToTop({
                            id: 'Main',
                            component: Main,
                            passProps: {},
                        });
                    } else {
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        Global.Const.token = ret.token;
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.push({
                            id: 'PerfectInformationContainer',
                            component: PerfectInformationContainer,
                            passProps: {
                                phone: this.state.inputphone,
                                token: ret.token,
                            },
                        });
                    }
                }).catch((err)=> {
                    dispatch({type: types.kUserLoginReceived, result: null});
                    this.setState({
                        submitting: false,
                    });
                });
                break;
            case 1:
                this.props.navigator.push({
                    id: 'ForgotPasswordContainer',
                    component: ForgotPasswordContainer,
                    passProps: {},
                });
                break;
        }
    }

    BackAction() {
        this.props.navigator.pop();
    }

    thirdLogin(type) {
        this.setState({
            submitting: true,
        });
        if (Platform.OS === 'android') {
            //登录类型   Wechat  SinaWeibo  QQ
            NativeModules.LoginShareModule.login(type, (msg) => {
                    if (msg[0].length < 10) {
                        this.setState({
                            submitting: false,
                        });
                        return;
                    }
                    console.log(msg[0]);
                    console.log(msg[1]);
                    console.log(msg[2]);
                    const {dispatch} = this.props;
                    UserAPIService.thirdLogin(msg[0], msg[1], msg[2], Global.Const.registeredId).then((ret)=> {
                        Global.Const.token = ret.token;
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        dispatch(userInfo(ret.token, Global.Const.registeredId));
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.popToTop({
                            id: 'Main',
                            component: Main,
                            passProps: {},
                        });


                    }).catch((err)=> {
                        this.setState({
                            submitting: false,
                        });
                        dispatch({type: types.kUserLoginReceived, result: null});
                    });
                },
                (result) => {
                    Toast.show('授权出错');
                    console.log('错误信息:' + result);
                    this.setState({
                        submitting: false,
                    });
                });
        }

        else if (Platform.OS === 'ios') {
            //登录类型   Wechat  SinaWeibo  QQ
            NativeModules.ShareSDK.login(type)
                .then((datas)=> {
                    const {dispatch} = this.props;
                    // dispatch(ThirdLoginAction(datas.nickname, datas.uid, datas.icon));
                    UserAPIService.thirdLogin(datas.uid, datas.nickname, datas.icon, Global.Const.registeredId).then((ret)=> {
                        Global.Const.token = ret.token;
                        dispatch({type: types.kUserLoginReceived, result: ret});
                        dispatch(userInfo(ret.token, Global.Const.registeredId));
                        this.setState({
                            submitting: false,
                        });
                        this.props.navigator.popToTop({
                            id: 'Main',
                            component: Main,
                            passProps: {},
                        });

                        console.log('接口登录成功:' + ret);
                        console.log('token------' + ret.token);


                    }).catch((err)=> {

                        this.setState({
                            submitting: false,
                        });
                        dispatch({type: types.kUserLoginReceived, result: null});
                        console.log('接口登录错误:' + err);


                    });

                    console.log('数据datas:', datas);

                    console.log('数据uid:' + datas.uid);
                    console.log('数据nickname:' + datas.nickname);
                    console.log('数据icon:' + datas.icon);
                    console.log('数据registeredId:' + Global.Const.registeredId);


                })
                .catch((err)=> {
                    this.setState({
                        submitting: false,
                    });
                    if (err.code === 'fail') {
                        Toast.show(err.message);
                    }
                    if (err.code === 'cancel') {
                        Toast.show(err.message);
                    }
                    this.setState({
                        submitting: false,
                    });
                });
        }


    }

    render() {
        return (
            <TouchableWithoutFeedback onPress={()=>this.closeKeybord()}>
                <View style={styles.container}>
                    <View style={{width:Global.Const.size.width,height:65,backgroundColor:'white'}}>

                        <View style={{marginTop:24,alignItems:'center'}}>

                            <View style={{width:21,height:21,position:'absolute',left:12,top:3}}>
                                <TouchableOpacity activeOpacity={0.5}
                                                  onPress={()=>this.BackAction()}>
                                    <Image style={{resizeMode:'contain',width:21,height:21}}
                                           source={require('../../Image/icon_back.png')}></Image>
                                </TouchableOpacity>
                            </View>
                            <Text style={{fontSize:19,color:Global.FontColor.DimGray}}>登录</Text>
                        </View>
                    </View>
                    <ScrollView>
                    <View
                        style={{flex:1,alignItems:'center',backgroundColor:'white', borderTopWidth:3,borderColor:Global.Const.transparent}}>
                        <Image style={{width:100,height:100,borderRadius:50,marginTop:50}}
                               source={require('../../Image/icon_logo.png')}></Image>

                        <View
                            style={{alignItems:'center',marginTop:30,width:Global.Const.size.width,height:45,backgroundColor:'white',flexDirection:'row'}}>
                            <Image style={{resizeMode:'contain',width:18,height:18,marginLeft:40}}
                                   source={require('../../Image/account_icon.png')}></Image>
                            <TextInput
                                style={{marginLeft:5,flex:1,fontSize:13}}
                                value={this.state.inputUserName}
                                onChangeText={inputUserName => this.setState({ inputUserName })}
                                placeholder={'请输入您的账号'}
                                maxLength={18}
                                keyboardType={'numeric'}
                                underlineColorAndroid={'transparent'}></TextInput>
                        </View>
                        <View
                            style={{width:Global.Const.size.width-80,height:1,backgroundColor:Global.Const.transparent,marginLeft:40,marginRight:40}}></View>
                        <View
                            style={{alignItems:'center',width:Global.Const.size.width,height:45,marginTop:15,backgroundColor:'white',flexDirection:'row'}}>
                            <Image style={{resizeMode:'contain',width:18,height:18,marginLeft:40}}
                                   source={require('../../Image/code_icon.png')}></Image>
                            <TextInput
                                style={{marginLeft:5,flex:1,fontSize:13}}
                                placeholder={'请输入您的密码'}
                                value={this.state.inputPassword}
                                onChangeText={inputPassword => this.setState({ inputPassword })}
                                maxLength={20}
                                secureTextEntry={true}
                                underlineColorAndroid={'transparent'}></TextInput>
                        </View>
                        <View
                            style={{width:Global.Const.size.width-80,height:1,backgroundColor:Global.Const.transparent,marginLeft:40,marginRight:40}}></View>
                        <TouchableOpacity activeOpacity={0.5}
                                          onPress={()=>this.ClickAction(1)}>
                            <View
                                style={{width:Global.Const.size.width,height:40,alignItems:'flex-end',justifyContent:'center'}}>
                                <Text style={{marginRight:45}}>忘记密码</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity activeOpacity={0.5}
                                          onPress={()=>this.ClickAction(0)}>
                            <View
                                style={{marginTop:25,backgroundColor:'#24CD78',borderRadius:20, marginLeft:30,marginRight:30,marginBottom:10,width:Global.Const.size.width-60,height:40, alignItems:'center',justifyContent:'center'}}>
                                <Text style={{color:'white',fontSize:18}}>登 录</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                    <View
                        style={{marginTop:30,width:Global.Const.size.width,height:120,backgroundColor:'white'}}>
                        <View
                            style={{width:Global.Const.size.width,height:40,flexDirection:'row',justifyContent:'center',alignItems:'center'}}>
                            <View style={{width:40,height:1,backgroundColor:Global.FontColor.LightGrey}}></View>
                            <Text
                                style={{marginLeft:5,marginRight:5,backgroundColor:'rgba(0,0,0,0)',color:Global.FontColor.LightGrey}}>免密码登录</Text>
                            <View style={{width:40,height:1,backgroundColor:Global.FontColor.LightGrey}}></View>
                        </View>
                        <View
                            style={{width:Global.Const.size.width,height:50,justifyContent:'center',alignItems:'center'}}>
                            <View style={{marginTop:10,flexDirection:'row'}}>
                                <View style={{width:50,height:50,borderRadius:25}}>
                                    <TouchableOpacity activeOpacity={0.5}
                                                      onPress={()=>this.thirdLogin('Wechat')}>
                                        <Image style={{width:50,height:50,borderRadius:25}}
                                               source={require('../../Image/wechat_icon.png')}></Image>
                                    </TouchableOpacity>
                                </View>
                                <View style={{width:50,height:50,borderRadius:25,marginLeft:25}}>
                                    <TouchableOpacity activeOpacity={0.5}
                                                      onPress={()=>this.thirdLogin('QQ')}>
                                        <Image style={{width:50,height:50,borderRadius:25}}
                                               source={require('../../Image/qq_icon.png')}></Image>
                                    </TouchableOpacity>
                                </View>
                                {/*<View style={{width:50,height:50,borderRadius:25}}>*/}
                                    {/*<TouchableOpacity activeOpacity={0.5}*/}
                                                      {/*onPress={*/}
                                                      {/*// ()=>this.thirdLogin('SinaWeibo')*/}
                                                      {/*()=>{*/}
                                                      {/**/}
                                                      {/*}*/}
                                                      {/*}>*/}
                                        {/*<Image style={{width:50,height:50,borderRadius:25}}*/}
                                               {/*source={require('../../Image/weibo_icon.png')}></Image>*/}
                                    {/*</TouchableOpacity>*/}
                                {/*</View>*/}
                            </View>
                        </View>
                    </View>
                    {this.state.submitting ? <View
                        style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                        <View
                            style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                            <ActivityIndicator
                                animating={this.state.animating}
                                style={{ alignItems: 'center',justifyContent: 'center'}}
                                size="large"/>
                            <Text style={{color:'white'}}>正在登录</Text>
                        </View>
                    </View> : null}
                    </ScrollView>
                </View>


            </TouchableWithoutFeedback>
        );
    }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white',
    },
});
